import Vue from 'vue'
import Vuex from 'vuex'
import {tranStr,tranObj ,removeInfo} from '../utils/saveInfo'
import home from './home'
import Search from './search'
import api from '@/api/index'

/* 关联sessionage */
const info = 'userinfo'

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    userinfo :tranObj(info),
    categoryList:[]
  },
  mutations: {
    saveInfo(state,payload){
      tranStr(info,payload)
      state[info] = tranObj(info)
    },
    rmInfo(state){
      removeInfo(state,info)
    },
    /* 请求Category */
  getCategory(state,L1){
    state.categoryList = L1
    }

  },
  actions: {
   async ac_category({commit}){
    const {result}= await api.reqCategory()
    
     const L1 = []
     const L2 = []
     result.forEach(item =>{
       if(item.level == 'L1'){
         L1.push(item)
       }else if(item.level == 'L2'){
         L2.push(item)
       }
     })
     /* 查找与父级ID相同子分类 */
     // 遍历父
     L1.forEach(item =>{
       item.child = []
       // 遍历子
       L2.forEach((citem,i)=>{
         if(item.id == citem.parent_id){
           item.child.push(citem);// 追加
         }
       })
     })

     /* 排序 */
     L1.forEach((item)=>{
       item.child.sort(function(x,y){
         return x.sort_order-y.sort_order
       })
     
     })

     /* 联动 */
     commit('getCategory',L1)

    }


  },
  modules: {
    home,
    Search

  }
})
